CommonJS简介

CommonJS简介

什么是commonjs

commonjs是module的一种类型(规范)

使用场景

CommonJS is mainly used in server-side JS apps with Node, as browsers don't support the use of CommonJS.
CommonJS 主要用于带有 Node 的服务器端 JS 应用程序,因为浏览器不支持使用 CommonJS。

如何使用

package.json

The "type" field defines the module format that Node.js uses for all .js files that have that package.json file as their nearest parent.
"type" 字段定义 Node.js 用于所有将该 package.json 文件作为其最近父级的 .js 文件的模块格式。
在package中不需要显示定义type(type的可选项是commonjs和module),一般是需要用到ESM的时候才去定义module。
package的影响范围是当前文件夹以及子文件夹的所有js文件。(ts会被ts编译器转化为js代码)

语法

导入:require 导出:module.exports
举个例子:

批量导入导出:

参考:
 
上一篇
国庆厦门&杭州之行
下一篇
messAuto + iMessage 实现iPhone和mac信息同步和自动复制验证码